package com.song.filter;

import com.song.base.util.JwtTemplate;
import com.song.base.util.RedisKeys;
import com.song.exception.AuthenticationException;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

@Configuration
@Component
@Slf4j
public class AuthenticationFilter implements GlobalFilter, Ordered {
    @Resource
    private JwtTemplate jwtTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getPath().toString();
        if(url.contains("/auth")) {
            //认证解析
            List<String> rs = exchange.getRequest().getHeaders().get("auth_token");
            if(rs == null || rs.size() <= 0) throw new AuthenticationException("没有登录",2001);
            String token = rs.get(0);
            Integer uid = null;
            try {
                Claims claims = jwtTemplate.parseJwt(token);
                log.info("claims:{}",claims);
                Object userId = claims.get("userId");
                uid = Integer.parseInt(userId.toString());
            }catch(Exception e) {
                throw new AuthenticationException("token解析错误",2002);
            }
            //取出用户权限级别
            HashOperations<String, Object, Object> ops = stringRedisTemplate.opsForHash();
            Object userPower = ops.get(RedisKeys.USER_AUTH_USER+uid, "UserPower");
            //菜单的权限级别
            String menuPower = url.substring(url.lastIndexOf("/") + 1);
            if(userPower==null||Integer.parseInt(menuPower)>(int)userPower){
                throw new AuthenticationException("权限不足",2004);
            }
        }
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return -1;
    }

}
